<!-- V-admin/src/views/dashboard/DashboardView.vue -->
<template>
  <div class="dashboard-container">
    <h1>数据概览</h1>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 数据内容 -->
    <div v-else>
      <!-- 数据统计卡片 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ stats.overview?.totalActivities || 0 }}</div>
              <div class="stat-label">活动总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ stats.overview?.totalProducts || 0 }}</div>
              <div class="stat-label">商品数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ stats.overview?.totalOrders || 0 }}</div>
              <div class="stat-label">订单数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">¥{{ stats.overview?.totalSales || 0 }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 内容区域 - 左两列右一列 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 左边两列 -->
        <el-col :span="16">
          <el-row :gutter="20">
            <!-- 今日数据 -->
            <el-col :span="24">
              <el-card style="height: 200px; margin-bottom: 20px;">
                <template #header>
                  <span>今日数据</span>
                </template>
                <div class="today-stats">
                  <div class="today-item">
                    <span class="label">新增预约：</span>
                    <span class="value">{{ stats.todayStats?.registrations || 0 }}</span>
                  </div>
                  <div class="today-item">
                    <span class="label">新增订单：</span>
                    <span class="value">{{ stats.todayStats?.orders || 0 }}</span>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <!-- 最近活动 -->
            <el-col :span="24">
              <el-card style="height: 400px;">
                <template #header>
                  <span>最近活动</span>
                  <el-button type="primary" text @click="$router.push('/activities')">查看全部</el-button>
                </template>
                <div v-if="stats.recentActivities && stats.recentActivities.length > 0" style="height: 320px; overflow-y: auto;">
                  <el-table :data="stats.recentActivities" style="width: 100%">
                    <el-table-column prop="title" label="活动名称"></el-table-column>
                    <el-table-column prop="anchor.name" label="主播">
                      <template #default="scope">
                        {{ scope.row.anchor?.name || '未知主播' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态">
                      <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                          {{ getStatusText(scope.row.status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div v-else class="empty-data">
                  暂无活动数据
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
        
        <!-- 右边一列 - 最近订单 -->
        <el-col :span="8">
          <el-card style="height: 620px;">
            <template #header>
              <span>最近订单</span>
              <el-button type="primary" text @click="$router.push('/orders')">查看全部</el-button>
            </template>
            <div v-if="stats.recentOrders && stats.recentOrders.length > 0" style="height: 540px; overflow-y: auto;">
              <el-table :data="stats.recentOrders" style="width: 100%">
                <el-table-column prop="order_number" label="订单号"></el-table-column>
                <el-table-column prop="audience.username" label="用户">
                  <template #default="scope">
                    {{ scope.row.audience?.username || '未知用户' }}
                  </template>
                </el-table-column>
                <el-table-column prop="total_amount" label="金额">
                  <template #default="scope">
                    ¥{{ scope.row.total_amount || 0 }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row.status)">
                      {{ getOrderStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="empty-data">
              暂无订单数据
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminAPI } from '../../api/admin'

const loading = ref(true)
const stats = ref<any>({
  overview: {},
  todayStats: {},
  recentActivities: [],
  recentOrders: []
})

// 活动状态映射
const getStatusType = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'published': 'success',
    'ongoing': 'warning',
    'completed': 'info',
    'cancelled': 'danger',
    'pending': 'default'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'published': '已发布',
    'ongoing': '进行中',
    'completed': '已完成',
    'cancelled': '已取消',
    'pending': '待审核'
  }
  return statusMap[status] || status
}

// 订单状态映射
const getOrderStatusType = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': 'warning',
    'paid': 'success',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger',
    'refunded': 'info'
  }
  return statusMap[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

const loadDashboardData = async () => {
  try {
    console.log('📊 开始加载仪表板数据...')
    loading.value = true
    
    // 调用真实API - 使用新的路径
    const response = await adminAPI.getDashboardStats()
    console.log('✅ API响应:', response)
    
    if (response.success) {
      stats.value = response.data
      console.log('📈 仪表板数据加载成功:', stats.value)
    } else {
      throw new Error(response.message || '数据加载失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载仪表板数据失败:', error)
    ElMessage.error('加载数据失败: ' + (error.message || '网络错误'))
    
    // 降级：使用模拟数据
    stats.value = {
      overview: {
        totalActivities: 15,
        totalProducts: 28,
        totalOrders: 89,
        totalSales: 15600.50
      },
      todayStats: {
        registrations: 5,
        orders: 3
      },
      recentActivities: [
        {
          title: '夏日音乐会',
          anchor: { name: 'T.七月' },
          status: 'published'
        },
        {
          title: '粉丝见面会',
          anchor: { name: 'T.七月' },
          status: 'ongoing'
        }
      ],
      recentOrders: [
        {
          order_number: 'ORD2024001',
          audience: { username: '用户123' },
          total_amount: 299.00,
          status: 'completed'
        },
        {
          order_number: 'ORD2024002', 
          audience: { username: '粉丝456' },
          total_amount: 158.00,
          status: 'paid'
        }
      ]
    }
    ElMessage.warning('使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stat-card {
  text-align: center;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-item {
  padding: 20px 0;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.today-stats {
  padding: 10px;
}

.today-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
}

.today-item .label {
  color: #606266;
}

.today-item .value {
  font-weight: bold;
  color: #409EFF;
}

.empty-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.loading-container {
  margin-top: 20px;
}
</style>